package com.bolovan.infovaluta.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.action.UrlBinding;

import com.bolovan.infovaluta.bean.ExchangeRate;
import com.bolovan.infovaluta.bean.ExchangeRateEntry;
import com.bolovan.infovaluta.bean.ExchangeRateSeller;
import com.bolovan.infovaluta.reader.BnrReader;
import com.bolovan.infovaluta.response.Response;
import com.bolovan.infovaluta.response.RoCompareResponse;
import com.bolovan.infovaluta.response.RoCompareResponseCurrency;
import com.bolovan.infovaluta.util.RateMaps;
import com.bolovan.infovaluta.util.RateUtil;

@UrlBinding("/api/rocompare.action")
public class RoCompare extends BaseAction {
	private static final Logger log = Logger.getLogger(RoCompare.class.getName());

	@DefaultHandler
	public Resolution addition() {
		ExchangeRate bnr = RateMaps.bnr;
		ExchangeRate bcr = RateMaps.bcr;
		ExchangeRate brd = RateMaps.brd;
		ExchangeRate bt = RateMaps.bt;
		ExchangeRate ing = RateMaps.ing;
		ExchangeRate raiffeisen = RateMaps.raiffeisen;
		
		try {
			bnr = new ExchangeRate(new BnrReader(ExchangeRateSeller.BNR));
		} catch (IOException e) {
			log.error("Error reading maps" + e.getMessage());
		}
		List<Set<ExchangeRateEntry>> rates = new ArrayList<>();
		List<RoCompareResponseCurrency> currencies = new ArrayList<>();
		if (bnr == null) {
			bnr = RateMaps.parseMap(ExchangeRateSeller.BNR);
		}
		if (bcr == null) {
			bcr = RateMaps.parseMap(ExchangeRateSeller.BCR);
		}
		if (brd == null) {
			brd = RateMaps.parseMap(ExchangeRateSeller.BRD);
		}
		if (bt == null) {
			bt = RateMaps.parseMap(ExchangeRateSeller.BT);
		}
		if (ing == null) {
			ing = RateMaps.parseMap(ExchangeRateSeller.ING);
		}
		if (raiffeisen == null) {
			raiffeisen = RateMaps.parseMap(ExchangeRateSeller.RAIFFEISEN);
		}
		rates.add(bnr.getCurrencyMap());
		rates.add(bcr.getCurrencyMap());
		rates.add(brd.getCurrencyMap());
		rates.add(bt.getCurrencyMap());
		rates.add(ing.getCurrencyMap());
		rates.add(raiffeisen.getCurrencyMap());

		for (ExchangeRateEntry e : RateMaps.bnr.getCurrencyMap()) {
			currencies.add(new RoCompareResponseCurrency(e.getCurrency(), e.getCurrencyDescr()));
		}
		RoCompareResponse response = new RoCompareResponse(currencies, rates);
		return new StreamingResolution("json", RateUtil.toJsonString(new Response<RoCompareResponse>(response)));
	}
}
